<template>
  <div ref="chartRef" class="chart"/>
</template>

<script setup>
import * as echarts from 'echarts'

import { set16ToRgb, getResponsiveSize } from '~utils/util.js'

const props = defineProps({
  chartData: {
    required: true,
    type: Object,
    default: () => {
      return {
        xData: [],
        seriesData: []
      }
    }
  },
  // y轴名称,
  yAxisName: {
    type: [String, Array],
    default: () => ''
  },
  unit: {
    type: String,
    default: () => ''
  },
  colorList: {
    type: Array,
    default: () => ['#28F2B2', '#28F0F2', '#28ADF2']
  },
  // 是否显示y轴分割线
  showYAxisSplitLine: {
    type: Boolean,
    default: () => true
  },
  // y轴分割线类型
  yAxisSplitLineType: {
    type: String,
    default: () => 'solid'
  }
})

const emit = defineEmits(['updateOp'])

const chartRef = ref(null)
let myChart = null

const chartOp = reactive({
  grid: {
    top: '18%',
    left: '6%',
    right: '6%',
    bottom: '8%',
    containLabel: true
  },
  legend: {
    selectedMode: false,
    itemWidth: 14,
    data: [],
    itemStyle: {
      borderWidth: 0
    },
    top: '5%'
  },
  tooltip: {
    trigger: 'axis',
    axisPointer: {
      type: 'line'
    },
    confine: true,
    backgroundColor: '#0b2247',
    borderColor: '#274e77',
    borderRadius: 8,
    textStyle: {
      zIndex: 100,
      fontSize: 12,
      color: '#fff'
    },
    formatter: params => {
      const resArr = reactive([params[0].name])
      for (let i = 0; i < params.length; i++) {
        const { seriesName, marker, value } = params[i]
        if (!seriesName.includes('-hidden')) {
          const str = `${marker}<span>${seriesName}: ${value}</span>`
          resArr.push(str)
        }
      }
      return resArr.join('<br />')
    }
  },
  xAxis: {
    axisTick: {
      show: false
    },
    boundaryGap: true,
    axisLabel: {
      color: '#C0E5F1',
      fontSize: 14,
      margin: 20
    },
    axisLine: {
      show: false
    },
    data: []
  },
  yAxis: [
    {
      name: '',
      nameTextStyle: {
        align: 'left',
        color: '#C0E5F1',
        padding: [0, 0, 0, -20]
      },
      type: 'value',
      axisTick: {
        show: false
      },
      splitLine: {
        show: props.showYAxisSplitLine,
        lineStyle: {
          color: 'rgba(89, 89, 89, 0.5)',
          type: props.yAxisSplitLineType
        }
      },
      axisLabel: {
        color: '#C0E5F1',
        fontSize: 14
      },
      data: []
    }
  ],
  series: []
})

const drawChart = () => {
  if (!chartRef.value) return
  if (myChart) {
    myChart.dispose()
  }
  myChart = echarts.init(chartRef.value, 'dark')

  const {
    colorList,
    yAxisName,
    chartData: { xData, seriesData }
  } = props
  chartOp.xAxis.data = xData
  if (Array.isArray(yAxisName)) {
    chartOp.yAxis.forEach((item, index) => {
      item.name = yAxisName[index]
    })
  } else {
    chartOp.yAxis[0].name = yAxisName
  }

  // 处理 series 数据
  const seriesArr = reactive([])
  seriesData.forEach((item, index) => {
    const { offsetX, data } = item

    const cubeData = [
      {
        name: '上方菱形-hidden',
        type: 'pictorialBar',
        symbol: 'diamond',
        symbolSize: [getResponsiveSize(54), getResponsiveSize(23)],
        symbolOffset: [offsetX, getResponsiveSize(-18)],
        symbolPosition: 'end',
        z: 5,
        data,
        itemStyle: {
          color: colorList[index],
          borderWidth: getResponsiveSize(4),
          borderColor: '#000'
        }
      },
      {
        name: item.name,
        type: 'pictorialBar',
        symbol: 'rect',
        symbolSize: [getResponsiveSize(54), '100%'],
        symbolOffset: [offsetX, getResponsiveSize(-7)],
        z: 3,
        data,
        symbolPosition: 'end',
        itemStyle: {
          borderWidth: 1,
          borderColor: '#000',
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [
              {
                offset: 0,
                color: set16ToRgb(colorList[index], 0.4)
              },
              {
                offset: 1,
                color: colorList[index]
              }
            ]
          }
        }
      },

      {
        name: '中间线-hidden',
        type: 'pictorialBar',
        symbol: 'rect',
        symbolSize: [1, '100%'],
        symbolOffset: [offsetX, 0],
        symbolPosition: 'start',
        z: 4,
        data,
        itemStyle: {
          color: '#fff',
          opacity: 0.3
        }
      },
      {
        name: '下方菱形-hidden',
        type: 'pictorialBar',
        symbol: 'diamond',
        symbolSize: [getResponsiveSize(54), getResponsiveSize(12)],
        symbolOffset: [offsetX, 0],
        symbolPosition: 'start',
        z: 4,
        data,
        itemStyle: {
          color: colorList[index]
        }
      }
    ]
    seriesArr.push(...cubeData)
  })

  chartOp.legend.data = seriesData.map((item) => item.name)
  chartOp.series = seriesArr
  chartOp.animationEasing = 'linear'
  chartOp.animationDelayUpdate = idx => {
    return idx * 300
  }

  emit('updateOp', chartOp)
  myChart.clear()
  myChart.setOption(chartOp)
}

watch(
  () => props.chartData,
  () => {
    nextTick(() => {
      drawChart()
    })
  },
  {
    immediate: true,
    deep: true
  }
)

const resizeChart = () => {
  if (myChart) {
    myChart.resize()
  }
}

onMounted(() => {
  window.addEventListener('resize', resizeChart)
})

onBeforeUnmount(() => {
  if (myChart) myChart.dispose()
  window.removeEventListener('resize', resizeChart)
})
</script>

<style lang="scss" scoped>
.chart {
	width: 100%;
	height: 100%;
}
</style>
